package com.hnzq.cloud.freshuserassembly.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.hnzq.cloud.dto.PageRolesDto;
import com.hnzq.cloud.dto.RoleDto;
import com.hnzq.cloud.freshuserassembly.domain.FreRole;
import com.hnzq.cloud.freshuserassembly.exception.FreshException;
import com.hnzq.cloud.freshuserassembly.exception.UserAccountException;
import com.hnzq.cloud.freshuserassembly.mapper.FreRoleMapper;
import com.hnzq.cloud.freshuserassembly.service.IFreRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hnzq.cloud.freshuserassembly.util.WoniuBeanUtils;
import com.hnzq.cloud.param.AddRoleParam;
import com.hnzq.cloud.param.DeleteRoleParam;
import com.hnzq.cloud.param.FindRolesParam;
import com.hnzq.cloud.param.UpdateRoleParam;
import org.redisson.api.RBucket;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 周皓月
 * @since 2022-02-03
 */
@Service
public class FreRoleServiceImpl extends ServiceImpl<FreRoleMapper, FreRole> implements IFreRoleService {

    /**
     * Redisson
     */
    @Resource
    private RedissonClient redisson;

    /**
     * 分页条件查询角色
     * @param findRolesParam
     * @return
     */
    @Override
    public PageRolesDto findRolesByCondition(FindRolesParam findRolesParam) {

        QueryWrapper<FreRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_delete", 0);

        //角色状态
        if (findRolesParam.getRoleStatus() != null && !findRolesParam.getRoleStatus().equals("")) {
            queryWrapper.eq("role_status",findRolesParam.getRoleStatus());
        }

        //大于等于开始时间
        if ( findRolesParam.getStartTime() != null && !findRolesParam.getStartTime().equals("")) {
            queryWrapper.ge("raw_add_time", findRolesParam.getStartTime());
        }

        //小于等于结束时间
        if (findRolesParam.getEndTime() != null && !findRolesParam.getEndTime().equals("")) {
            queryWrapper.le("raw_add_time", findRolesParam.getEndTime());
        }

        if (findRolesParam.getKeyWord() != null && !findRolesParam.getKeyWord().trim().equals("")) {
            queryWrapper.and(qw -> {
                qw.like("role_name", findRolesParam.getKeyWord()).or()
                        .like("role_id", findRolesParam.getKeyWord());
            });
        }

        IPage<FreRole> iPage = page(new Page<>(findRolesParam.getIndexPage()
                , findRolesParam.getPageSize()),queryWrapper);

        PageRolesDto pageRolesDto = new PageRolesDto();
        pageRolesDto.setCurrent(iPage.getCurrent());
        pageRolesDto.setTotal(iPage.getTotal());
        pageRolesDto.setRoleDtoList(WoniuBeanUtils.copyList(iPage.getRecords(), RoleDto.class));

        return pageRolesDto;
    }

    /**
     * 新增角色
     * @param addRoleParam
     * @return
     */
    @Override
    public RoleDto addRole(AddRoleParam addRoleParam) {

        //根据名字查询数据库，看是否有重复名字
        FreRole roleDB = getOne(new QueryWrapper<FreRole>().eq("role_name", addRoleParam.getRoleName()));
        if (roleDB != null){
            throw new UserAccountException("角色名已存在",1006);
        }
        //执行新增操作
        saveOrUpdate(WoniuBeanUtils.copyObject(addRoleParam, FreRole.class));

        return WoniuBeanUtils.copyObject(addRoleParam,RoleDto.class);
    }

    /**
     * 更新角色
     * @param updateRoleParam
     * @return
     */
    @Override
    public RoleDto updateRoleById(UpdateRoleParam updateRoleParam) throws JsonProcessingException {

        //获取锁对象
        RLock lock = redisson.getLock("updateRoleById");

        //是否获取锁
        if (lock.tryLock()){
            //从redis查询对象
            RBucket<Object> bucket = redisson.getBucket("roleId:" + updateRoleParam.getRoleId());

            if (!bucket.isExists()){
                //查询数据库是否存在
                FreRole roleDB = getById(updateRoleParam.getRoleId());
                if (roleDB == null){
                    lock.unlock();
                    throw new UserAccountException("需更新的角色不存在",1007);
                }
                //设置参数后再存redis
                if (updateRoleParam.getRoleName() != null && !updateRoleParam.getRoleName().trim().equals("")){
                    roleDB.setRoleName(updateRoleParam.getRoleName());
                }
                if (updateRoleParam.getRoleStatus() != null && !updateRoleParam.getRoleStatus().equals("")){
                    roleDB.setRoleStatus(updateRoleParam.getRoleStatus());
                }
                //把从数据库查的对象存放redis
                bucket.set(roleDB,2, TimeUnit.HOURS);

                //执行更新操作
                saveOrUpdate(WoniuBeanUtils.copyObject(updateRoleParam,FreRole.class));
                //操作完数据库后解锁
                lock.unlock();
                return WoniuBeanUtils.copyObject(updateRoleParam,RoleDto.class);
            }
            //执行更新操作
            saveOrUpdate(WoniuBeanUtils.copyObject(updateRoleParam,FreRole.class));
            //设置参数后再存redis
            FreRole redisRole = (FreRole) bucket;
            if (updateRoleParam.getRoleName() != null && !updateRoleParam.getRoleName().trim().equals("")){
                redisRole.setRoleName(updateRoleParam.getRoleName());
            }
            if (updateRoleParam.getRoleStatus() != null && !updateRoleParam.getRoleStatus().equals("")){
                redisRole.setRoleStatus(updateRoleParam.getRoleStatus());
            }
            //把从数据库查的order对象存放redis
            bucket.set(redisRole,2,TimeUnit.HOURS);

            //操作完数据库后解锁
            lock.unlock();
            return WoniuBeanUtils.copyObject(updateRoleParam,RoleDto.class);
        }else {
            throw new FreshException("服务器繁忙，请稍后再试",5005);
        }
    }

    /**
     * 删除角色
     * @param deleteRoleParam
     * @return
     */
    @Override
    public Boolean deleteRoleById(DeleteRoleParam deleteRoleParam) throws JsonProcessingException {

        //获取锁对象
        RLock lock = redisson.getLock("deleteRoleById");

        //是否获取锁
        if (lock.tryLock()){
            //从redis查询对象
            RBucket<Object> bucket = redisson.getBucket("roleId:" + deleteRoleParam.getRoleId());

            if (!bucket.isExists()){
                //先查询数据库是否存在
                FreRole roleDB = getById(deleteRoleParam.getRoleId());
                if (roleDB == null){
                    lock.unlock();
                    throw new UserAccountException("需删除的角色不存在",1008);
                }
                //设置参数后再存redis
                if (deleteRoleParam.getIsDelete() != null && !deleteRoleParam.getIsDelete().equals("")){
                    roleDB.setIsDelete(deleteRoleParam.getIsDelete());
                }
                //把从数据库查的对象存放redis
                bucket.set(roleDB,2, TimeUnit.HOURS);

                //执行删除操作
                boolean bool = saveOrUpdate(WoniuBeanUtils.copyObject(deleteRoleParam, FreRole.class));
                //操作完数据库后解锁
                lock.unlock();
                return bool;
            }
            //执行删除操作
            boolean bool = saveOrUpdate(WoniuBeanUtils.copyObject(deleteRoleParam, FreRole.class));
            //设置参数后再存redis
            FreRole redisRole = (FreRole) bucket.get();
            //设置参数后再存redis
            if (deleteRoleParam.getIsDelete() != null && !deleteRoleParam.getIsDelete().equals("")){
                redisRole.setIsDelete(deleteRoleParam.getIsDelete());
            }
            //把从数据库查的order对象存放redis
            bucket.set(redisRole,2,TimeUnit.HOURS);

            //操作完数据库后解锁
            lock.unlock();
            return bool;
        }else {
            throw new FreshException("服务器繁忙，请稍后再试",5005);
        }
    }
}
